"""应用中间件."""

from fastapi import FastAPI, Request
from fastapi.responses import Response

from app.core.config import settings
from app.core.result import fail


def add_middlewares(app: FastAPI) -> None:
    """添加所有中间件."""
    add_cors_middleware(app)
    add_application_exception_middleware(app)


def add_cors_middleware(app: FastAPI) -> None:
    """添加 CORS 中间件."""
    from fastapi.middleware.cors import CORSMiddleware

    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.CORS_ORIGIN,
        allow_methods=settings.CORS_METHODS,
        allow_headers=settings.CORS_ALLOWED_HEADERS,
        allow_credentials=settings.CORS_CREDENTIALS,
        expose_headers=settings.CORS_EXPOSE_HEADERS,
        max_age=settings.CORS_MAX_AGE,
    )


def add_application_exception_middleware(app: FastAPI) -> None:
    """添加应用异常处理中间件."""
    from app.core.exception import ApplicationException
    from app.utils.logger import get_logger

    logger = get_logger("app.middleware.exception")

    @app.exception_handler(ApplicationException)
    async def application_exception_handler(
        request: Request, exc: ApplicationException
    ) -> Response:
        """处理应用异常."""
        logger.error(f"❌ {exc.message}", **(exc.meta if exc.meta is not None else {}))
        return Response(
            fail(type(exc).__name__, exc.message).model_dump_json(),
            media_type="application/json",
        )
